import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, current_app, g, render_template
from flask_migrate import Migrate
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from redis import StrictRedis

from config import conf


db = None    #type:SQLAlchemy
sr = None    #type:StrictRedis

def setup_log(log_level):
    # 设置日志的记录等级
    logging.basicConfig(level=log_level)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(pathname)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


# 工厂函数
def create_app(type):

    # 创建app
    app = Flask(__name__)
    # 导入开发配置
    config = conf[type]
    app.config.from_object(config)
    global db,sr
    # 创建数据库
    db = SQLAlchemy(app)
    # 连接数据库
    sr = StrictRedis(host=config.REDIS_IP,port=config.REDIS_PORT,decode_responses=True)
    # 创建session
    Session(app)
    # 创建迁移对象
    Migrate(app,db)

    #用的时候导入
    from info.modules.home import home_blu
    #注册蓝图
    app.register_blueprint(home_blu)
    from info.modules.passpornt import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    from info.modules.user import user_blu
    app.register_blueprint(user_blu)
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    setup_log(config.LOG_LEVEL)

    # 导入模块文件
    from info import models
    # 模板中加入过滤器
    from info.utils.common import func_index_convert
    app.add_template_filter(func_index_convert,"index_convert")

    from info.utils.common import user_login_data
    #全局捕获404错误
    @app.errorhandler(404)
    @user_login_data
    def page_not_found(e):
        current_app.logger.error(e)
        user = g.user.to_dict() if g.user else None
        return render_template("news/404.html",user=user)


    return app